//
//  QXAccount.swift
//  QXWeibo
//
//  Created by QinXin on 15/6/25.
//  Copyright © 2015年 labi3285_Lab. All rights reserved.
//

import UIKit
import AFNetworking

class QXAccount: NSObject, NSCoding {
    
    // 令牌
    var access_token: String
    // 当前使用时间
    var expires_in: NSTimeInterval
    // 用户id
    var uid: String
    
    var avatar_large: String?
    var name: String?
    
    // 过期时间
    var expiresDate: NSDate
    
    class func loadAccount() -> QXAccount? {
        
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? QXAccount {
            if account.expiresDate.compare(NSDate()) == NSComparisonResult.OrderedDescending {
                return account
            }
        }
        return nil
    }
    
    init(dic: [String: AnyObject]) {
        access_token = dic["access_token"] as! String
        expires_in = dic["expires_in"] as! NSTimeInterval
        uid = dic["uid"] as! String
        expiresDate = NSDate(timeIntervalSinceNow: expires_in)
    }
    
    // 这个方法里的闭包方便授权界面根据是否成功进行回調
    func loadUserInfo(success:(account: QXAccount?) -> (), failed:(error: NSError?) -> ()) {
                
        let params = ["access_token": access_token, "uid": uid]
        QXNetworking.sharedNetworking().GET("2/users/show.json", parameters: params, success: { (_, data) -> Void in
            
            let dic = data as! [String: AnyObject]
            
            self.name = dic["name"] as? String
            self.avatar_large = dic["avatar_large"] as? String
            
            self.saveAccount()
            
            // 这句话很重要
            sharedAccount = self
            
            success(account: self)
            
            }) { (_, error) -> Void in
                
                failed(error: error)
        }
        
    }
    
    override var description: String {
        let properties = ["access_token", "expires_in", "uid", "expiresDate", "name", "avatar_large"]
        return "\(self.dictionaryWithValuesForKeys(properties))"
    }
    
    static let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingPathComponent("account.plist")
    
    func saveAccount() {
        NSKeyedArchiver.archiveRootObject(self, toFile: QXAccount.accountPath)
    }
    
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as! String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as! NSDate
        uid = aDecoder.decodeObjectForKey("uid") as! String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }

}
